package com.dh.Linked;

import org.junit.Test;

public class Linked {
	private int size;//链表的个数
	private Node head;//头节点
	
	public Linked(){
		size=0;
		head=null;
	}
	
	/**
	 * 链表对象
	 * @author liguobao
	 *
	 */
	private class Node{
		private Object data;
		private Node next;
		public Node(Object data) {
			this.data=data;
		}
	}
	
	/**
	 * 在链表头部添加节点
	 * @return
	 */
	public Object addHead(Object obj) {
		Node newHead=new Node(obj);
		if(size==0) {
			head=newHead;
		}else {
			newHead.next=head;
			head=newHead;
		}
		size++;
		return obj;
	}
	
	/**
	 * 在链表头删除节点
	 * @return
	 */
	public Object deleteHead() {
		Object obj=head.data;
		head=head.next;
		size--;
		return obj;
	}
	
	/**
	 * 查找指定元素
	 * @param obj
	 * @return
	 */
	public Node find(Object obj) {
		Node current=head;
		int tempSize=size;
		while(tempSize>0) {
			if(obj.equals(current.data)) {
				return current;
			}else {
				current=current.next;
			}
			tempSize--;
		}
		return null;
	}
	
	/**
	 * 删除指定元素
	 * @param value
	 * @return
	 */
	public boolean delete(Object value) {
		if(size==0) {
			return false;
		}
		Node current=head;
		Node previous=head;
		for(int i=1;i<=size;i++) {
			if(current.data==value) {
				//删除的是头节点
				if(current==head) {
					head=current.next;
					size--;
				}else {
					previous.next=current.next;
					size--;
				}
				return true;
			}else {
				if(current.next==null) {
					return false;
				}
				previous=current;
				current=current.next;
			}
		}
		return false;
	}
	
	public boolean isEmpty() {
		return (size == 0);
	}
	
	//显示节点信息
	public void display(){
      if(size >0){
          Node node = head;
          int tempSize = size;
          if(tempSize == 1){//当前链表只有一个节点
              System.out.println("["+node.data+"]");
              return;
          }
          while(tempSize>0){
              if(node.equals(head)){
                 System.out.print("["+node.data+"->");
             }else if(node.next == null){
                 System.out.print(node.data+"]");
             }else{
                 System.out.print(node.data+"->");
             }
             node = node.next;
             tempSize--;
         }
         System.out.println();
     }else{//如果链表一个节点都没有，直接打印[]
         System.out.println("[]");
     }  
   }
      
  @Test
  public void testSingleLinkedList(){
	  	Linked singleList = new Linked();
	    singleList.addHead("A");
	    singleList.addHead("B");
	    singleList.addHead("C");
	    singleList.addHead("D");
	    //打印当前链表信息
	    singleList.display();
	    //删除C
	    singleList.delete("C");
	    singleList.display();
	    //查找B
	    System.out.println(singleList.find("B"));
	}
}
